package edgeTSQL

import (
	"errors"
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Slice"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Sort"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"strings"
	"time"
)

func QueryRecords(body map[string]interface{}) ([]*edgeEntity.DeviceSequenceEntity, error) {
	if API == nil {
		return nil, errors.New("没有绑定具体的数据库API实现")
	}

	recordTime := Map.GetInt64(body, "recordTime", 0)
	order := strings.ToUpper(Map.GetString(body, "order", "ASC"))

	// 查询相关数据表表
	times, err := QueryTableTimes()
	if err != nil {
		return nil, err
	}

	// 对数据库表名的时间，进行排序
	orderTables(times, order)

	// 根据时间进行限定
	if _, ok := body["recordTime"]; ok {
		times = limitByRecordTime(times, recordTime, order)
	}

	// 查询分页数据
	list, err := queryRecords(times, body)
	if err != nil {
		return nil, err
	}

	return list, nil
}

func BuildMapList(entityList []*edgeEntity.DeviceSequenceEntity) []map[string]interface{} {
	list := make([]map[string]interface{}, 0)
	for _, entity := range entityList {
		po := entity.BuildToPo()
		mp := Json.BuildMap(po)
		list = append(list, mp)
	}

	return list
}

func QueryTableTimes() ([]int64, error) {
	if API == nil {
		return nil, errors.New("没有绑定具体的数据库API实现")
	}

	// 取得数据库表名称
	tableNames, err := API.QueryTableNames(tableName)
	if err != nil {
		return nil, err
	}

	// 转换为数字
	times := make([]int64, 0)
	for _, tblName := range tableNames {
		time := tblName[len(tableName)+1:]
		times = append(times, Number.ParseInt64(time))
	}

	return times, nil
}

func orderTables(times []int64, order string) {
	// 排序
	order = strings.ToUpper(order)
	Sort.Sort(times, func(t1, t2 interface{}) bool {
		if order == "DESC" {
			return t2.(int64) < t1.(int64)
		} else {
			return t1.(int64) < t2.(int64)
		}
	})
}

func queryRecords(times []int64, body map[string]interface{}) ([]*edgeEntity.DeviceSequenceEntity, error) {
	pageSize := Map.GetInt(body, "pageSize", 10)

	result := make([]*edgeEntity.DeviceSequenceEntity, 0)
	for _, num := range times {
		tblName := tableName + "_" + fmt.Sprintf("%010d", num)
		list, err := API.QueryRecords(tblName, body)
		if err != nil {
			return nil, err
		}

		if len(result)+len(list) < pageSize {
			result = Slice.Append(result, list)
			continue
		} else if len(result)+len(list) == pageSize {
			result = Slice.Append(result, list)
			break
		} else {
			result = Slice.Append(result, list[:pageSize-len(result)])
			break
		}
	}

	return result, nil
}

func limitByRecordTime(times []int64, recordTime int64, order string) []int64 {
	// 准备处理的数据库表
	ready := make([]int64, 0)
	start := Number.ParseInt64(time.UnixMilli(recordTime).Format("2006010215"))
	for _, val := range times {
		if order == "ASC" {
			if start <= val {
				ready = append(ready, val)
			}
		} else {
			if start >= val {
				ready = append(ready, val)
			}
		}
	}

	return ready
}
